package common

import (
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
)

type Response struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
	Time string      `json:"time"`
}

// 通用响应方法
func (r *Response) Send(c *gin.Context) {
	c.JSON(r.Code, r)
}

// 成功响应
func Success(data interface{}) *Response {
	return &Response{
		Code: 200,
		Msg:  "success",
		Data: data,
		Time: time.Now().Format("2006-01-02 15:04:05"),
	}
}

// 失败响应
func Fail(code int, msg string) *Response {
	return &Response{
		Code: code,
		Msg:  msg,
		Data: nil,
		Time: time.Now().Format("2006-01-02 15:04:05"),
	}
}

// 直接发送成功响应
func ResponseSuccess(c *gin.Context, data interface{}) {
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "success",
		"data": data,
		"time": time.Now().Format("2006-01-02 15:04:05"),
	})
}

// 直接发送错误响应
func ResponseError(c *gin.Context, statusCode int, message string) {
	c.JSON(statusCode, gin.H{
		"code": statusCode,
		"msg":  message,
		"data": nil,
		"time": time.Now().Format("2006-01-02 15:04:05"),
	})
}
